<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-12-02 18:59:00
 * @LastEditors: Andy
 * @LastEditTime: 2023-02-28 17:46:04
-->
<template>
  <x-dialog :title="title" :show.sync="visible" v-if="visible" :before-close="handleClose" width="35%">
    <el-form :model="params" class="demo-form-inline" ref="params" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="24" v-if="params.parentId + '' !== '0'">
          <el-form-item :label="$t('organization.dept.preDept')" prop="parentId">
            <x-select-tree
              ref="selecTree"
              v-model="params.parentId"
              :options="deptTreeData"
              :defaultProps="defaultDeptProps"
              :placeholder="$t('system.user.pleaseSelect')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('organization.dept.name')" prop="deptName">
            <el-input v-model="params.deptName" :placeholder="$t('system.user.remarktxt')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('organization.dept.code')" prop="deptCode">
            <el-input v-model="params.deptCode" :placeholder="$t('system.user.remarktxt')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('organization.dept.shortName')" prop="shortName">
            <el-input v-model="params.shortName" :placeholder="$t('system.user.remarktxt')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('organization.dept.sort')" prop="sort">
            <el-input-number size="small" v-model="params.sort" controls-position="right" :min="1"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('organization.dept.toStart')" prop="state">
            <x-radio-group :list-data="dictOptions['system.state']" v-model="params.state"></x-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button @click="handleClose"> {{ $t('common.cancel') }} </el-button>
      <el-button
        type="primary"
        @click="
          loading = true
          handleSubmit()
        "
        :loading="loading"
      >
        {{ $t('common.confirm') }}
      </el-button>
      <!-- <el-button
        v-if="params.parentId && params.parentId + '' === '0' && params?.id"
        type="danger"
        @click="handleDeleteDept"
      >
        {{ $t('common.delete') }}
      </el-button> -->
    </span>
  </x-dialog>
</template>
<script>
  import { cloneDeep, omit, throttle } from '@package/utils'
  import { apiPostAddDept, apiPostEditDept, apiPostDeptTree } from '../api'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  export default {
    props: {
      defaultDeptProps: {
        type: Object,
        default: () => ({})
      },
      dictOptions: {
        type: Object,
        default: () => ({})
      },
      orgId: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        title: '',
        visible: false,
        loading: false,
        deptTreeData: [],
        params: {
          parentId: '',
          deptName: '',
          deptCode: '',
          orgId: this.orgId,
          shortName: '',
          sort: '',
          state: '1'
        },
        rules: {
          parentId: [{ required: true, message: this.$t('organization.dept.preDeptPlaceholder'), trigger: 'blur' }],
          deptName: [
            { required: true, message: this.$t('organization.dept.namePlaceholder'), trigger: 'blur' },
            { min: 1, max: 30, message: this.$t('organization.dept.nameLength'), trigger: 'blur' }
          ],
          deptCode: [
            { required: true, message: this.$t('organization.dept.codeplaceholder'), trigger: 'blur' },
            { min: 1, max: 30, message: this.$t('organization.dept.nameLength'), trigger: 'blur' }
          ],
          shortName: [
            { required: true, message: this.$t('organization.dept.shortNameplaceholder'), trigger: 'blur' },
            { min: 1, max: 30, message: this.$t('organization.dept.nameLength'), trigger: 'blur' }
          ],
          sort: [],
          state: [{ required: true, message: this.$t('organization.dept.statePlaceholder'), trigger: 'blur' }]
        }
      }
    },
    created() {},
    methods: {
      async handleOpen(info) {
        await this.loadTreeData(info.orgId)
        this.visible = true
        this.params.parentId = info?.parentId ?? 0
        if (info?.id || info?.value) {
          this.title = this.$t('organization.dept.editDept')
          this.$nextTick(() => {
            this.params = Object.assign(this.params, cloneDeep(info))
            this.params.state = this.params.state += ''
            this.params.deptName = this.params?.label ?? this.params.deptName
            this.params.id = this.params?.value ?? this.params.id
            this.params.orgId = info?.orgId ?? 0
          })
          return
        }
        this.title = this.$t('organization.dept.addDept')
      },
      async loadTreeData(orgId) {
        const { data, code, msg } = await apiPostDeptTree({ state: 1, orgId })
        if (code === EnumApiCode.Success) {
          this.deptTreeData = data
        } else {
          this.$message.error(msg)
        }
      },
      getDeptInfo(id) {},

      handleSubmit: throttle(function () {
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            const id = this.$refs.selecTree?.currentNode.value ?? this.params.parentId
            const orgId = this.$refs.selecTree?.currentNode.orgId ?? this.params.orgId
            const param = {
              ...this.params,
              orgId: orgId || this.orgId,
              parentId: id
            }
            try {
              const { code, msg } = 'id' in this.params ? await apiPostEditDept(param) : await apiPostAddDept(param)
              this.loading = false
              if (code === EnumApiCode.Success) {
                this.$message.success(
                  'id' in this.params ? this.$t('common.editSuccess') : this.$t('common.newSuccess')
                )
                this.$emit('handleSuccess', true)
                this.handleClose()
              } else {
                this.$message.error(msg)
              }
            } finally {
              this.loading = false
            }
          } else {
            this.loading = false
            return false
          }
        })
      }, 1000),
      handleClose() {
        this.$refs.params.resetFields()
        this.params = omit(this.params, 'id')
        this.params.parentId = '0'
        this.visible = false
      },
      handleDeleteDept() {
        this.$emit('on-delete', this.params.id)
        this.handleClose()
      }
    }
  }
</script>
